package com.fishsticks.view;



import com.fishsticks.model.DatabaseManager;
import com.fishsticks.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


/**
 * First activity started in To-Do List app
 * Lets the user register or login
 */
public class LoginActivity extends Activity
{
	private TextView usernameField, passwordField;
	private Button registerButton, loginButton;
	private AlertDialog.Builder dialog;
	private Bundle extras;
	public boolean test = false;

    /**
     * Called when the activity is first created.
     * Creates button click listeners and intents to
     * switch between login/register activities
     * */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        this.setContentView(R.layout.login_page);

        registerButton = (Button) findViewById(R.id.registerButtonLoginPage);
        loginButton = (Button) findViewById(R.id.loginButtonLoginPage);

        usernameField = (TextView) findViewById(R.id.usernameFieldLoginPage);
        passwordField = (TextView) findViewById(R.id.passwordFieldLoginPage);

        dialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.white_orange_dialog));
        
        
        // Gets recently created username if coming 
        // from the registration page
        extras = getIntent().getExtras();
        if(extras != null) 
        {
        	usernameField.setText(extras.getString("username"));
        }
        




        registerButton.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0)
			{
				//Switches to register screen
				Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
				startActivity(i);
				finish();
			}
        });





        loginButton.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0)
			{
				//check for blank fields
				if(checkValidFields(usernameField.getText().toString(), passwordField.getText().toString()))
				{
					//check login credentials
					if(checkCredentials(usernameField.getText().toString(), passwordField.getText().toString()))
					{
						/*
						//Show dialog box for successful login
						dialog.setTitle("Success");
				    	dialog.setMessage("Login successful! *do more stuff later*");
				    	dialog.setButton("Woohoo!", new android.content.DialogInterface.OnClickListener()
				    	{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								dialog.dismiss();
							}

				    	});
				    	dialog.show();
				    	*/
				    
				    	//Switch to main To-Do List Screen if login is correct
						test = true;
				    	Intent i = new Intent(getApplicationContext(), ToDoListActivity.class);
				    	i.putExtra("username", usernameField.getText().toString());
						startActivity(i);
					}
					
					else if(!checkIfValidUsername(usernameField.getText().toString()))
					{
						dialog.setTitle("Error");
				    	dialog.setMessage("The username doesn't exist. Please register before logging in.");
				    	dialog.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener()
				    	{
				    		//Hides dialog after user clicks "ok" button
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								dialog.dismiss();
							}

				    	});
				    	dialog.setPositiveButton("Go Register", new android.content.DialogInterface.OnClickListener()
				    	{
				    		//Goes to register screen
				    		public void onClick(DialogInterface dialog, int which) {
								Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
								i.putExtra("username", usernameField.getText().toString());
								i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(i);
							}

				    	});
				    	dialog.show();
					}

					//Show alert for incorrect credentials
					else
					{
						dialog.setTitle("Error");
				    	dialog.setMessage("The username or password is invalid.");
				    	dialog.setPositiveButton("Okay", new android.content.DialogInterface.OnClickListener()
				    	{
				    		//Hides dialog after user clicks "ok" button
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								dialog.dismiss();
							}

				    	});
				    	dialog.show();
					}
				}


				//Show alert for blank fields
				else
				{
			    	dialog.setTitle("Fields are blank");
			    	dialog.setMessage("The username and password fields cannot be blank.");
			    	dialog.setPositiveButton("Okay", new android.content.DialogInterface.OnClickListener()
			    	{
			    		//Hides dialog after user clicks "ok" button
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();
						}

			    	});
			    	dialog.show();
				}
			}
        });
    }






    /**
     * Checks the log in credentials with database manager
     *
     * @param username The username to check
     * @param password The password to check
     * @return A boolean representing whether or not the login
     *         credentials are valid in the DB
     */
    public boolean checkCredentials(String username, String password)
    {
    	DatabaseManager dm = new DatabaseManager(this);
    	boolean success = dm.checkCredentials(username, password);
    	dm.close();
    	return success;
    }
    
    
    
    
    /**
     * Checks for a valid username with database manager
     *
     * @param username The username to check
     * @return A boolean representing whether or 
     * 		   not the username exists in the DB
     */
    public boolean checkIfValidUsername(String username)
    {
    	DatabaseManager dm = new DatabaseManager(this);
    	boolean success = dm.checkIfUsernameExists(username);
    	dm.close();
    	return success;
    }





    /**
     * Checks if the username or password fields are blank
     * and alerts the user if they are
     *
     * @param username The username to check
     * @param password The password to check
     * @return A boolean representing whether or not the fields are blank
     */
    public boolean checkValidFields(String username, String password)
    {

    	if(username.length() != 0)
    	{
    		if(password.length() != 0)
    			return true;

    		else
    			return false;
    	}

    	else
    		return false;
    }
}